import 'package:card_swiper/card_swiper.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:shenfuhui/config/config.dart';
import 'package:shenfuhui/routers/routers.dart';

import '../entity/banner_entity.dart';
import '../http/api.dart';
import '../utils/user_utils.dart';
import '../views/home_index_top_layout.dart';
import '../views/mall_home_module.dart';
import '../views/marquee_widget.dart';

class HomeIndex extends StatefulWidget {
  const HomeIndex({Key? key}) : super(key: key);

  @override
  State<HomeIndex> createState() => _HomeIndexState();
}

class _HomeIndexState extends State<HomeIndex> {
  var imgs = [];
  var menus = [];
  var menusSub = [];
  int currentMenuIndex = 0;
  var anns = ['奥运礼品系列仅限中银visa奥运信用卡持卡人', '2023年春节假期服务公告'];
  GlobalKey<HomeIndexTopLayoutState> homeTopKey = GlobalKey();

  @override
  void initState() {
    super.initState();
    getData();
  }

  @override
  void dispose() {
    super.dispose();
  }

  getData() async {
    imgs.add(
        "https://www.shyaki.com/uploadfile/2021/0111/20210111052443839.jpg");
    imgs.add(
        "https://picnew13.photophoto.cn/20181201/lunbotutaobaoshuangshier-31074489_1.jpg");

    menus.add('电脑办公');
    menus.add('美妆护肤');
    menus.add('家具家装');
    menus.add('内衣配饰');
    menus.add('运动户外');
    menus.add('食品酒饮');
    menus.add('二手商品');

    menusSub.add('Computer');
    menusSub.add('Beauty');
    menusSub.add('Furniture');
    menusSub.add('Underwear');
    menusSub.add('Exercise');
    menusSub.add('Foodstuff');
    menusSub.add('Second');
  }

  //返回商品列表item
  getListItem(int index) {
    return InkWell(
      onTap: () {
        Routes.navigateTo(context, Routes.productDetail,
            params: {'productId': '001'});
      },
      child: Container(
        decoration: BoxDecoration(
          color: Config.colorWhite,
          borderRadius: BorderRadius.circular(10.w),
        ),
        child: Column(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(10.w),
              child: Image.network(
                'https://bkimg.cdn.bcebos.com/pic/dc54564e9258d109b3de9cb75d14dbbf6c81800ae728',
                fit: BoxFit.fill,
                height: 320.w,
              ),
            ),
            Padding(padding: EdgeInsets.all(5.w)),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 15.w),
              width: double.infinity,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Padding(padding: EdgeInsets.only(top: 2.w)),
                  Text(
                    '商品名称',
                    style: TextStyle(color: Config.colorText1, fontSize: 28.sp),
                  ),
                  Padding(padding: EdgeInsets.only(top: 10.w)),
                  Text(
                    '商品简短介绍',
                    style: TextStyle(color: Config.colorText3, fontSize: 24.sp),
                    overflow: TextOverflow.ellipsis,
                    maxLines: 1,
                  ),
                  Padding(padding: EdgeInsets.only(top: 10.w)),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '￥0.00',
                        style:
                            TextStyle(color: Colors.redAccent, fontSize: 24.sp),
                      ),
                      Text(
                        '库存1',
                        style: TextStyle(
                            color: Config.colorText3, fontSize: 24.sp),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///
  /// 金刚区的Item
  ///
  Widget getJingangItem(String imgUrl, String name, Function() onTap) {
    return InkWell(
      onTap: onTap,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.network(
            imgUrl,
            fit: BoxFit.fill,
            width: 75.w,
            height: 75.w,
          ),
          Text(name,
              style: TextStyle(
                  fontSize: 21.sp, height: 1.8, color: Config.colorText1)),
        ],
      ),
    );
  }

  //返回菜单item
  getMenuItem(int position) {
    return InkWell(
      onTap: () {
        setState(() {
          currentMenuIndex = position;
        });
      },
      child: Container(
        padding: EdgeInsets.fromLTRB(18.w, 0, 18.w, 0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Padding(padding: EdgeInsets.all(5.w)),
            currentMenuIndex == position
                ? Text(
                    menus[position],
                    style:
                        TextStyle(color: (Config.colorMain), fontSize: 30.sp),
                  )
                : Text(
                    menus[position],
                    style:
                        TextStyle(color: (Config.colorText1), fontSize: 30.sp),
                  ),
            currentMenuIndex == position
                ? Text(
                    menusSub[position],
                    style:
                        TextStyle(color: (Config.colorMain), fontSize: 23.sp),
                  )
                : Text(
                    menusSub[position],
                    style:
                        TextStyle(color: (Config.colorText3), fontSize: 23.sp),
                  ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    ScrollController controller = ScrollController();
    controller.addListener(() {
      if (controller.offset > 100) {
        return;
      }
      // print("监听滚动的位置 ${controller.offset}");
      homeTopKey.currentState?.upDateLayoutBg(controller.offset / 100);
    });

    return Scaffold(
      body: Container(
        padding: const EdgeInsets.all(0),
        width: double.infinity,
        decoration: const BoxDecoration(color: Config.colorBg2),
        height: double.infinity,
        child: Stack(
          children: [
            EasyRefresh.builder(
              header: const MaterialHeader(),
              footer: const MaterialFooter(),
              onRefresh: () async {
                await Future.delayed(const Duration(seconds: 1), () {
                  print('refresh');
                });
              },
              onLoad: () async {
                await Future.delayed(const Duration(seconds: 1), () {
                  print('load');
                });
              },
              childBuilder: (context, physics) {
                return ListView(
                  scrollDirection: Axis.vertical,
                  controller: controller,
                  physics: physics,
                  padding: const EdgeInsets.all(0),
                  children: [
                    SizedBox(
                      //轮播
                      height: 550.w,
                      child: Swiper(
                        itemBuilder: (BuildContext context, int index) {
                          return Image.network(
                            imgs[index],
                            fit: BoxFit.fill,
                          );
                        },
                        onTap: (index) {
                          Routes.navigateTo(context, Routes.productSpecial,
                              params: {'pageTitle': "测试专区标题"});
                        },
                        autoplay: true,
                        layout: SwiperLayout.DEFAULT,
                        itemCount: imgs.length,
                        // viewportFraction: 0.7,
                        // scale: 0.8,
                        pagination: SwiperPagination(
                          builder: DotSwiperPaginationBuilder(
                              // size: Size(20.w, 4.w),
                              // activeSize: Size(20.w, 4.w),
                              size: 15.w,
                              activeSize: 15.w,
                              activeColor: Config.colorMain,
                              color: Config.colorWhite),
                        ),
                      ),
                    ),
                    Container(
                      height: 90.w,
                      margin:
                          EdgeInsets.only(top: 30.w, left: 25.w, right: 25.w),
                      padding: EdgeInsets.symmetric(horizontal: 20.w),
                      decoration: BoxDecoration(
                        color: Config.colorWhite,
                        borderRadius: BorderRadius.circular(12.w),
                      ),
                      child: InkWell(
                        onTap: () {
                          Routes.router.navigateTo(context, Routes.announcement,
                              transition: TransitionType.inFromRight);
                        },
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Row(
                              children: [
                                Text(
                                  "公告",
                                  style: TextStyle(
                                      fontSize: 25.w, color: Config.colorText1),
                                ),
                                Padding(
                                  padding: EdgeInsets.only(left: 20.w),
                                ),
                                Container(
                                  height: 36.w,
                                  width: 400.w,
                                  child: MarqueeWidget(
                                    //子Item构建器
                                    itemBuilder:
                                        (BuildContext context, int index) {
                                      String itemStr = anns[index];
                                      //通常可以是一个 Text文本
                                      return Text(
                                        itemStr,
                                        style: TextStyle(fontSize: 25.w),
                                      );
                                    },
                                    //循环的提示消息数量
                                    count: anns.length,
                                  ),
                                ),
                              ],
                            ),
                            Icon(
                              Icons.arrow_forward_ios,
                              size: 25.w,
                              color: Config.colorText3,
                            ),
                          ],
                        ),
                      ),
                    ),
                    Container(
                      //金刚区
                      width: double.infinity,
                      margin: EdgeInsets.only(top: 35.w),
                      child: SizedBox(
                        height: 270.w,
                        child: GridView.count(
                          padding: EdgeInsets.symmetric(
                              vertical: 10.w, horizontal: 0.w),
                          mainAxisSpacing: 18.w,
                          childAspectRatio: 1.6,
                          crossAxisSpacing: 0,
                          crossAxisCount: 4,
                          physics: const NeverScrollableScrollPhysics(),
                          children: [
                            getJingangItem(
                                'https://img1.baidu.com/it/u=3397604428,133270066&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
                                "礼遇专区", () async {
                              // if (await UserUtils.isLogin(context) == false) {
                              //   return;
                              // }
                              Routes.navigateTo(context, Routes.productSpecial,
                                  params: {'pageTitle': "测试专区标题"});
                            }),
                            getJingangItem(
                                'https://img1.baidu.com/it/u=3397604428,133270066&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
                                "生态商城", () async {
                              // if (await UserUtils.isLogin(context) == false) {
                              //   return;
                              // }
                              Routes.navigateTo(context, Routes.productSpecial,
                                  params: {'pageTitle': "测试专区标题"});
                            }),
                            getJingangItem(
                                'https://img1.baidu.com/it/u=3397604428,133270066&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
                                "活动预告", () async {
                              // if (await UserUtils.isLogin(context) == false) {
                              //   return;
                              // }
                              Routes.navigateTo(context, Routes.productSpecial,
                                  params: {'pageTitle': "测试专区标题"});
                            }),
                            getJingangItem(
                                'https://img1.baidu.com/it/u=3397604428,133270066&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
                                "抖音推荐", () {
                              // if (await UserUtils.isLogin(context) == false) {
                              //   return;
                              // }
                              Routes.navigateTo(context, Routes.productSpecial,
                                  params: {'pageTitle': "测试专区标题"});
                            }),
                            getJingangItem(
                                'https://img1.baidu.com/it/u=3397604428,133270066&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
                                "热门精选", () {
                              // if (await UserUtils.isLogin(context) == false) {
                              //   return;
                              // }
                              Routes.navigateTo(context, Routes.productSpecial,
                                  params: {'pageTitle': "测试专区标题"});
                            }),
                            getJingangItem(
                                'https://img1.baidu.com/it/u=3397604428,133270066&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
                                "优惠专区", () async {
                              // if (await UserUtils.isLogin(context) == false) {
                              //   return;
                              // }
                              Routes.navigateTo(context, Routes.productSpecial,
                                  params: {'pageTitle': "测试专区标题"});
                            }),
                            getJingangItem(
                                'https://img1.baidu.com/it/u=3397604428,133270066&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
                                "免费水果", () async {
                              // if (await UserUtils.isLogin(context) == false) {
                              //   return;
                              // }
                              Routes.navigateTo(context, Routes.productSpecial,
                                  params: {'pageTitle': "测试专区标题"});
                            }),
                            getJingangItem(
                                'https://img1.baidu.com/it/u=3397604428,133270066&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
                                "PLUS会员", () async {
                              // if (await UserUtils.isLogin(context) == false) {
                              //   return;
                              // }
                              Routes.navigateTo(context, Routes.productSpecial,
                                  params: {'pageTitle': "测试专区标题"});
                            }),
                          ],
                        ),
                      ),
                    ),
                    getMallHomeModule1(
                        'https://img.zcool.cn/community/01abc85a9e162aa801219586dc141c.jpg@1280w_1l_2o_100sh.jpg'),
                    getMallHomeModule3(
                        'https://img2.baidu.com/it/u=2389364918,140145626&fm=253&fmt=auto&app=120&f=JPEG?w=640&h=1136',
                        'https://img2.baidu.com/it/u=2389364918,140145626&fm=253&fmt=auto&app=120&f=JPEG?w=640&h=1136',
                        'https://img2.baidu.com/it/u=2389364918,140145626&fm=253&fmt=auto&app=120&f=JPEG?w=640&h=1136'),
                    getMallHomeModule4(
                      'https://doc-fd.zol-img.com.cn/t_s640x2000/g7/M00/07/03/ChMkK2L3hauIbXtNAAIbk9nCLpUAAGcgAAh7VEAAhur956.jpg',
                      'https://img1.baidu.com/it/u=2267064549,147968865&fm=253&fmt=auto&app=138&f=JPEG?w=952&h=500',
                      'https://x0.ifengimg.com/res/2021/9C8349DE18CB566531EE8D37E867483F1121600D_size42_w1097_h685.jpeg',
                      'https://img0.baidu.com/it/u=1761007641,3990492183&fm=253&fmt=auto&app=138&f=JPEG?w=979&h=500',
                    ),
                    // getMallHomeModule6(
                    //     'https://n.sinaimg.cn/finance/transform/184/w630h354/20220905/dd76-db80ee162c520a218bdd7e698e0b5714.jpg',
                    //     'https://pad.mydrivers.com/img/20170510/0dfa56aeace14b49959052d1c6ec6c9d.jpg',
                    //     'https://img2.baidu.com/it/u=3066156497,2399437797&fm=253&fmt=auto&app=138&f=JPG?w=400&h=300',
                    //     'https://img2.baidu.com/it/u=407732994,1382908239&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=506',
                    //     'https://pic1.zhimg.com/v2-6438843a4cbae9184b935a75a5059ac6_1440w.jpg?source=172ae18b',
                    //     'https://img2.baidu.com/it/u=1323202793,3644150238&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500'),
                    getMallHomeModule5(
                      'https://pics6.baidu.com/feed/b7003af33a87e950d990202d55d1144bf9f2b4da.jpeg?token=f7aadb16068f7accdf1bca5d1679bbe1',
                      'https://img2.baidu.com/it/u=3066156497,2399437797&fm=253&fmt=auto&app=138&f=JPG?w=400&h=300',
                      'https://pic1.zhimg.com/v2-6438843a4cbae9184b935a75a5059ac6_1440w.jpg?source=172ae18b',
                      'https://img0.baidu.com/it/u=1707266565,2130578631&fm=253&fmt=auto&app=120&f=JPEG?w=667&h=500',
                      'https://img2.baidu.com/it/u=407732994,1382908239&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=506',
                    ),
                    getMallHomeModuleToday(),
                    Container(
                      width: double.infinity,
                      margin: EdgeInsets.only(top: 25.w),
                      height: 100.w,
                      child: ListView.builder(
                        itemCount: menus.length,
                        padding: EdgeInsets.only(left: 10.w, right: 15.w),
                        shrinkWrap: true,
                        scrollDirection: Axis.horizontal,
                        physics: const BouncingScrollPhysics(),
                        itemBuilder: (BuildContext context, int index) {
                          return getMenuItem(index);
                        },
                      ),
                    ),
                    Container(
                      margin: EdgeInsets.fromLTRB(20.w, 30.w, 20.w, 20.w),
                      decoration:
                          const BoxDecoration(color: Colors.transparent),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          SizedBox(
                            width: double.infinity,
                            child: GridView.builder(
                              padding: EdgeInsets.symmetric(horizontal: 0.w),
                              itemCount: 10,
                              shrinkWrap: true,
                              scrollDirection: Axis.vertical,
                              physics: const NeverScrollableScrollPhysics(),
                              itemBuilder: (BuildContext context, int index) {
                                return getListItem(index);
                              },
                              gridDelegate:
                                  SliverGridDelegateWithFixedCrossAxisCount(
                                      crossAxisCount: 2,
                                      mainAxisSpacing: 19.w,
                                      crossAxisSpacing: 19.w,
                                      childAspectRatio: 0.72),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                );
              },
            ),
            HomeIndexTopLayout(
              key: homeTopKey,
            ),
          ],
        ),
      ),
    );
  }
}
